﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class RoleDA : IRoleDA
    {
        private string COPY_ROLE_ID = "@COPY_ROLE_ID";
        private string CREATED_BY = "@CREATED_BY";
        private string IS_ACTIVE = "@IS_ACTIVE";
        private string ROLE_ID = "@ROLE_ID";
        private string ROLE_NAME = "@ROLE_NAME";
        private string SQL_CHECK_ROLE_ID_UNIQUE = " SELECT COUNT(1) FROM @_@ROLE WHERE ROLE_ID = @ROLE_ID ";
        private string SQL_DELETE_ROLE = " DELETE FROM @_@ROLE WHERE ROLE_ID = @ROLE_ID AND SYSTEM_CREATED = 'N' ";
        private string SQL_INSERT_ROLE = " INSERT INTO @_@ROLE ( ROLE_ID, ROLE_NAME, IS_ACTIVE, SYSTEM_CREATED, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @ROLE_ID, @ROLE_NAME, @IS_ACTIVE, @SYSTEM_CREATED, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_ROLE = " SELECT  ROWID, ROLE_ID, ROLE_NAME, IS_ACTIVE, SYSTEM_CREATED, TS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@ROLE ";
        private string SQL_UPDATE_ROLE = " UPDATE @_@ROLE SET ROLE_NAME = @ROLE_NAME, IS_ACTIVE = @IS_ACTIVE, SYSTEM_CREATED = @SYSTEM_CREATED, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE ROLE_ID = @ROLE_ID  ";
        private string SYSTEM_CREATED = "@SYSTEM_CREATED";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";

        public bool CheckRoleIDUnique(string roleID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_ROLE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckRoleIDUnique(DataBase dataBase, DbTransaction tran, string roleID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_ROLE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteRole(List<string> roleID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < roleID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteRole(DataBase dataBase, DbTransaction tran, List<string> roleID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < roleID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllRole(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_ROLE.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllRole(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_ROLE.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public RoleInfo GetRoleByID(string roleID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_ROLE.Replace("@_@", whLoginID) + " WHERE ROLE_ID = @ROLE_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleID) };
            RoleInfo roleInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    roleInfo = new RoleInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["ROLE_ID"].ToString(), reader["ROLE_NAME"].ToString(), reader["IS_ACTIVE"].ToString(), reader["SYSTEM_CREATED"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return roleInfo;
        }

        public RoleInfo GetRoleByID(DataBase dataBase, DbTransaction tran, string roleID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_ROLE.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleID) };
            RoleInfo roleInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                roleInfo = new RoleInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["ROLE_ID"].ToString(), reader["ROLE_NAME"].ToString(), reader["IS_ACTIVE"].ToString(), reader["SYSTEM_CREATED"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return roleInfo;
        }

        public DataSet GetRoleByQueryList(List<string> sqlWhere, RoleQueryEntity roleQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_ROLE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!roleQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, roleQuery.CurrentPage, roleQuery.PageSize, roleQuery.SortField, roleQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetRoleByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, RoleQueryEntity roleQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_ROLE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!roleQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, roleQuery.CurrentPage, roleQuery.PageSize, roleQuery.SortField, roleQuery.SortDirection);
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertRole(RoleInfo roleInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_Role_Parameters(roleInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertRole(DataBase dataBase, DbTransaction tran, RoleInfo roleInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_Role_Parameters(roleInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int RoleCopy(DataBase dataBase, DbTransaction tran, string strCopyRoleID, RoleInfo roleInfo)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.Append("  INSERT INTO SYSADM.ROLE_FUNCTION( ROLE_ID,FUNCTION_ID,CREATED_BY,CREATED_DATE,UPDATED_BY,UPDATED_DATE ) ");
            StrSql.Append("  SELECT @ROLE_ID,FUNCTION_ID,@CREATED_BY,GETDATE(),@UPDATED_BY,GETDATE() FROM SYSADM.ROLE_FUNCTION WHERE ROLE_ID=@COPY_ROLE_ID ");
            StrSql.Append("  INSERT INTO SYSADM.ROLE_OPERATION( ROLE_ID,OPERATION_ID,CREATED_BY,CREATED_DATE,UPDATED_BY,UPDATED_DATE ) ");
            StrSql.Append("  SELECT @ROLE_ID,OPERATION_ID,@CREATED_BY ,GETDATE(),@UPDATED_BY,GETDATE()  FROM SYSADM.ROLE_OPERATION  WHERE ROLE_ID=@COPY_ROLE_ID ");
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROLE_ID", roleInfo.RoleID), new SqlParameter("@CREATED_BY", roleInfo.CreatedBy), new SqlParameter("@UPDATED_BY", roleInfo.CreatedBy), new SqlParameter("@COPY_ROLE_ID", strCopyRoleID) };
            return dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.ToString(), paras);
        }

        private SqlParameter[] Set_Role_Parameters(RoleInfo roleInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.ROLE_ID, SqlDbType.VarChar, 20), new SqlParameter(this.ROLE_NAME, SqlDbType.VarChar, 50), new SqlParameter(this.IS_ACTIVE, SqlDbType.VarChar, 1), new SqlParameter(this.SYSTEM_CREATED, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = roleInfo.RoleID;
            if (!string.IsNullOrEmpty(roleInfo.RoleName))
            {
                paramArray[1].Value = roleInfo.RoleName;
            }
            else
            {
                paramArray[1].Value = DBNull.Value;
            }
            paramArray[2].Value = roleInfo.IsActive;
            paramArray[3].Value = roleInfo.SystemCreated;
            paramArray[4].Value = roleInfo.CreatedBy;
            paramArray[5].Value = roleInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateRole(RoleInfo roleInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_Role_Parameters(roleInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateRole(DataBase dataBase, DbTransaction tran, RoleInfo roleInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_Role_Parameters(roleInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

